package remote.mvc.delegates
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	
	import remote.mvc.commands.IResponse;
	
	/**
	 * 主动式代理的一种，使用Loader获取数据的代理
	 * @createDate 2011-2-28
	 * @author 徐俊杰
	 */
	public class URLLoaderDelegate
	{
		private var _response:IResponse;
		private var _url:String;
		
		private var _loader:URLLoader;
		
		/**
		 * 实例化 LoaderDelegate
		 * @param response 返回结果后的处理类
		 * @param url 通讯路径
		 * 
		 */		
		public function URLLoaderDelegate(response:IResponse)
		{
			_response = response;
			_loader = new URLLoader();
		}
		
		public function load(url:String, data:Object = null):void
		{
			_loader.addEventListener(Event.COMPLETE, loader_completeHandler);
			_loader.addEventListener(IOErrorEvent.IO_ERROR, loader_ioErrorHandler);
			_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loader_securityErrorHandler);
			
			var request:URLRequest = new URLRequest(url);
			if(data != null)
			{
				request.data = data;
				request.method = URLRequestMethod.POST;
			}
			_loader.load(request);
		}
		
		public function stop():void
		{
			removeListeners();
			_loader.close();
		}
		
		private function removeListeners():void
		{
			_loader.removeEventListener(Event.COMPLETE, loader_completeHandler);
			_loader.removeEventListener(IOErrorEvent.IO_ERROR, loader_ioErrorHandler);
			_loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, loader_securityErrorHandler);
		}
		
		private function loader_completeHandler(e:Event):void
		{
			removeListeners();
			_response.result(_loader.data);
		}
		
		private function loader_ioErrorHandler(e:IOErrorEvent):void
		{
			removeListeners();
			_response.fault(e.text);
		}
		
		private function loader_securityErrorHandler(e:SecurityErrorEvent):void
		{
			removeListeners();
			_response.fault(e.text);
		}
	}
}